<template>
  <div class="search">
    <Row :gutter="16" class="all-height">
      <Col :span="showRight ? 18 : 24" class="all-height">
        <Card class="all-height card-child-height">
          <div style="display: flex; justify-content: space-between; align-items: center; height: 40px">
            <div style="display: flex; flex-wrap: nowrap; overflow-x: auto">
              <Button @click="add" type="primary" icon="md-add">新增</Button>
              <Button @click="handleReset" icon="md-refresh">刷新</Button>
              <Button  type="primary" icon="ios-cloud-upload-outline"
                      @click="importFormView = true">导入用人单位信息
              </Button>
              <Button  @click="downloadTemple" type="info">下载导入模板</Button>
              <Button  @click="dropExportData">导出所选数据</Button>
              <Button :loading="importing1"  @click="dropExportAll">导出全部数据</Button>
              <!--<Button @click="dropExportAll" icon="">导入用人单位信息</Button>-->
              <!--              <Button type="dashed" @click="openTip=!openTip">{{openTip ? "关闭提示" : "开启提示"}}</Button>-->
            </div>
            <Col span="2" style="text-align: right">
              <Icon
                  color="#fff"
                  style="background: rgb(45, 154, 244); border-radius: 50%; padding: 3px"
                  :type="!showRight ? `ios-arrow-back` : `ios-arrow-forward`"
                  @click.native="clickShowRight"
              ></Icon>
            </Col>
          </div>
          <div class="mt-12" style="height: 40px" v-show="openTip">
            <Alert show-icon>
              已选择
              <span class="select-count">{{ selectList.length }}</span>
              项
              <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert>
          </div>

          <div class="mt-12" style="height: calc(100% - 104px)">
            <div class="tableContainer ">
              <div v-if="loading" class="wh-100 d-flex-around-center">
                <Spin></Spin>
              </div>
              <div v-else v-ref-height="abca" class="wh-100">
                <el-table v-if="data.length > 0" :loading="listLoading" ref="table" :height="abca.value" :data="data" empty-text="暂无数据"
                          border @selection-change="handleSelectionChange" style="width: 100%">
                  <el-table-column type="selection" :width="tableWidth"></el-table-column>
                  <el-table-column type="index" label="序号" :width="tableWidth"></el-table-column>
                  <el-table-column prop="name" label="单位名称"></el-table-column>
                  <el-table-column prop="status" label="经营状态">
                    <template slot-scope="scope">
                      <span v-if="scope.row.status === '0'">正常</span>
                      <span v-if="scope.row.status === '1'">吊销</span>
                      <span v-if="scope.row.status === '2'">注销</span>
                      <span v-if="scope.row.status === '3'">其他</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="code" width="160" label="统一社会信息代码"></el-table-column>
                  <el-table-column prop="nature" label="单位性质" width="200">
                    <template slot-scope="scope">
                      {{getunitNature(scope.row.nature)}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="industry" label="单位行业">
                    <template slot-scope="scope">
                      {{getunitIndustry(scope.row.industry)}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" width="120" label="单位所在地代码"></el-table-column>
                  <el-table-column prop="contactPerson" width="120" label="单位联系人"></el-table-column>
                  <el-table-column prop="contactPhone" width="120" label="联系电话"></el-table-column>
                  <el-table-column prop="location" width="200" label="单位所在地"></el-table-column>
                  <el-table-column prop="remarkOne" label="标签一"></el-table-column>
                  <el-table-column prop="remarkTwo" label="标签二"></el-table-column>
                  <el-table-column prop="remarkThree" label="标签三"></el-table-column>
                  <el-table-column prop="remarkFour" label="标签四"></el-table-column>
                  <el-table-column prop="remarkFive" label="标签五"></el-table-column>
                  <el-table-column fixed="right" width="120" label="操作">
                    <template slot-scope="scope">
                      <el-button @click="viewYdData(scope.row)" type="text" size="small">编辑</el-button>
                      <el-button type="text" size="small" @click="remove(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-else class="wh-100">
                  <NoData class="wh-100"></NoData>
                </div>
              </div>
            </div>

            <div class="d-flex-center" style="height: 100px">
              <Page
                  :current="searchForm.pageNumber"
                  :total="total"
                  :page-size="searchForm.pageSize"
                  @on-change="changePage"
                  @on-page-size-change="changePageSize"
                  :page-size-opts="[10, 20, 50]"
                  size="small"
                  show-total
                  show-elevator
                  show-sizer
              ></Page>
            </div>

          </div>
        </Card>
      </Col>
      <Col span="6" class="all-height" v-show="showRight">
        <Card class="all-height card-child-height">
          <Row v-show="openSearch" @keydown.enter.native="handleSearchB">
            <Col span="24">
              <div class="drawer-header">
                <div style="margin-right: 16px">查询区</div>
              </div>
            </Col>
            <Col span="24">
              <Form ref="searchForm" :model="searchForm" :label-width="labelWidth" class="marginForm">
                <FormItem label="单位名称" >
                  <Input type="text" v-model="searchForm.name" clearable placeholder="请输入单位名称" style="width: 100%"
                         @click.prevent="$event.preventDefault()"/>
                </FormItem>
                <FormItem label="经营状态" >
                  <Select v-model="searchForm.status" clearable
                          style="width: 100%">
                    <Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                  </Select>
                </FormItem>
                <FormItem label="统一社会信用代码" >
                  <Input type="text" v-model="searchForm.code" clearable placeholder="请输入统一社会信用代码" style="width: 100%"
                         @click.prevent="$event.preventDefault()"/>
                </FormItem>
                <FormItem label="单位性质" >
                  <Select v-model="searchForm.nature" clearable style="width: 100%">
                    <Option v-for="(item,index) in unitNatureDicts" :value="item.value" :key="index">{{ item.title }}
                    </Option>
                  </Select>
                </FormItem>
                <FormItem label="单位行业" >
                  <Select v-model="searchForm.industry" clearable
                          style="width: 100%">
                    <Option v-for="(item,index) in unitIndustryDicts" :value="item.value" :key="index">{{ item.title }}
                    </Option>
                  </Select>
                </FormItem>
                <FormItem label="标签一" >
                  <Input type="text" v-model="searchForm.remarkOne" clearable placeholder="请输入标签一" style="width: 100%"
                         @click.prevent="$event.preventDefault()"/>
                </FormItem>
                <FormItem label="标签二" >
                  <Input type="text" v-model="searchForm.remarkTwo" clearable placeholder="请输入标签一" style="width: 100%"
                         @click.prevent="$event.preventDefault()"/>
                </FormItem>
                <FormItem label="标签三" >
                  <Input type="text" v-model="searchForm.remarkThree" clearable placeholder="请输入标签一" style="width: 100%"
                         @click.prevent="$event.preventDefault()"/>
                </FormItem>
                <FormItem label="标签四" >
                  <Input type="text" v-model="searchForm.remarkFour" clearable placeholder="请输入标签一" style="width: 100%"
                         @click.prevent="$event.preventDefault()"/>
                </FormItem>
                <FormItem label="标签五" >
                  <Input type="text" v-model="searchForm.remarkFive" clearable placeholder="请输入标签一" style="width: 100%"
                         @click.prevent="$event.preventDefault()"/>
                </FormItem>
                <FormItem class="br mt-12 mb-12 box-key">
                  <Button @click="handleSearchB" type="primary" icon="ios-search">搜索</Button>
                  <Button @click="handleReset">重置</Button>
                </FormItem>
              </Form>
            </Col>
          </Row>
          <Row class="calc-sm-height" v-show="!openSearch"  v-loading="loading">
            <addEdit :data="form" :type="showType" v-model="showDrawer" :unitIndustryDicts="unitIndustryDicts" @submit="submit" @cancel="openSearch=true"
                     :unitNatureDicts="unitNatureDicts" ref="compareDetail"  :statusList="statusList" @on-submit="getDataList" />
          </Row>
        </Card>
      </Col>
    </Row>
    <Modal
        v-model="importFormView"
        title="导入用人单位信息">
      <Form :model="importForm" :label-width="80">
        <!--<div>注:导入档案信息时，请先导入生源信息，否则无法导入档案信息。</div>-->
        <FormItem label="文件: ">
          <Upload
              accept=".xls,.xlsx"
              :before-upload="handleUpload">
            <Button icon="ios-cloud-upload-outline">点击上传</Button>
          </Upload>
        </FormItem>
        <FormItem label=" ">
          <div v-if="importForm.file !== null">
            {{ importForm.file.name }}
          </div>
          <div>说明：请依据模板数据格式导入，文件格式必须为.xlsx</div>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="importFormcCncel">取消</Button>
        <Button type="primary" :loading="importing" @click="importFormOk">开始上传</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
// 根据你的实际请求api.js位置路径修改
import {
  getBysXjCompareList,
  exportAllBysXjInfo,
  deleteBysXjCompare,
  exportBatchMarketDataAPI
} from '@/api/bys/xj/xjCompare.js';
import {companiesPageAPI,companiesUpdateAPI,companiesAddAPI,companiesDeleteAPI, exportAll} from "@/api/bys/companies/index"
// 根据你的实际添加编辑组件位置路径修改
import addEdit from './addEdit.vue';
import Cookies from 'js-cookie';
import NoData from '@/components/NoData.vue';
import { getDictDataByType } from '@/api';
import { newAllProvincialDataApi } from '@/api/bys';
import { importArchiveTransferInfoAPI } from '@/api/archivesManagement/archiveForwardingAddressApis';
import { easyExcelImportData } from '@/api/bys/xj/bysXjInfo';

export default {
  name: 'bysXjCompare',
  components: {
    addEdit,
    NoData,
  },
  data() {
    return {
      importing1:false,
      importFormView:false,
      importing:false,
      importForm: {
        file: null,
        importMode: '1'
      },
      listLoading: false,
      tableWidth: 60,
      labelWidth: 110,
      resource: '',
      abca: {value: 0},
      cardId: '',
      status: '',
      bysId: '',
      height1: 0,
      openSearch: true,
      showRight: true,
      openTip: true, // 显示提示
      showType: '0', // 添加或编辑标识
      showDrawer: false, // 显示添加编辑抽屉
      loading: false, // 表单加载状态
      searchForm: {
        // 搜索框初始化对象
        pageNumber: 1, // 当前页数
        pageSize: 20, // 页面大小
        "code": "",
        "industry": "",
        "name": "",
        "nature": "",
        status: '',
        remarkOne:'',
        remarkTwo:'',
        remarkThree:'',
        remarkFour:'',
        remarkFive:'',
      },
      selectList: [], // 多选数据
      form: {},
      statusList: [
        {value: '0', label: '正常'},
        {value: '1', label: '吊销'},
        {value: '2', label: '注销'},
        {value: '3', label: '其他'}
      ],
      unitNatureDicts:[],
      unitIndustryDicts:[],
      columns: [
        // 表头
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '序号',
          type: 'index',
          width: 70,
          align: 'center'
        },
        {
          title: '单位名称',
          key: 'name',
          minWidth: 120,
          sortable: false
        },
        {
          title: '经营状态',
          key: 'schoolName',
          minWidth: 120,
          align: 'center'
        },
        {
          title: '院系名称',
          key: 'xsh',
          minWidth: 120,
          sortable: false
        },
        {
          title: '专业',
          key: 'speciality',
          minWidth: 120,
          sortable: false
        },
        {
          title: '考生号',
          key: 'ksh',
          minWidth: 180,
          sortable: false
        },
        {
          title: '身份证号',
          key: 'idCard',
          minWidth: 180,
          sortable: false
        },
        {
          title: '状态',
          key: 'status',
          minWidth: 120,
          sortable: false
        },
        {
          title: '操作人',
          key: 'person',
          minWidth: 120,
          sortable: false
        },
        {
          title: '操作时间',
          key: 'time',
          minWidth: 120,
          sortable: false
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 150,
          render: (h, params) => {
            let viewYdData = '';
            if (!params.row.sfyyd) {
              viewYdData = h(
                  'a',
                  {
                    on: {
                      click: () => {
                        this.viewYdData(params.row);
                      }
                    }
                  },
                  '查看'
              );
            }
            return h('div', [
              viewYdData,
              h('Divider', {
                props: {
                  type: 'vertical'
                }
              }),
              h(
                  'a',
                  {
                    on: {
                      click: () => {
                        this.remove(params.row);
                      }
                    }
                  },
                  '删除'
              )
            ]);
          }
        }
      ],
      data: [], // 表单数据
      pageNumber: 1, // 当前页数
      pageSize: 10, // 页面大小
      total: 0 // 表单数据总数
    };
  },
  // provide() {
  //     return {
  //         getDataList: this.getDataList
  //     };
  // },
  methods: {
    getunitNature(index){
      let val = '';
      this.unitNatureDicts.map(item=>{
        if (index == item.value){
          val = item.title;
        }
      })
      return val
    },
    getunitIndustry(index){
      let val = '';
      this.unitIndustryDicts.map(item=>{
        if (index == item.value){
          val = item.title;
        }
      })
      return val
    },
    async getDictData() {
      //单位性质
      await getDictDataByType('unit-nature').then(res => {
        if (res.success) {
          this.unitNatureDicts = res.result;
        }
      });
      // 单位行业
      await getDictDataByType('unit-industry').then(res => {
        if (res.success) {
          this.unitIndustryDicts = res.result;
        }
      });
    },
    handleSelectionChange(val) {
      this.selectList = val;
    },
    init() {
      // this.getDataList();
      this.getDataListB();
      this.openSearch =true
    },
    // 显示隐藏右侧区域
    clickShowRight() {
      this.showRight = !this.showRight;
    },
    // handleSearchA() {
    //     this.searchForm.cardId = this.cardId;
    //
    //     this.searchForm.status = '';
    //     this.getDataList();
    // },
    handleSearchB() {
      this.getDataListB();
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      // this.getDataList();
      this.getDataListB();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      // this.getDataList();
      this.getDataListB();
    },

    handleReset() {
      this.searchForm= {
        // 搜索框初始化对象
        pageNumber: 1, // 当前页数
        pageSize: 20, // 页面大小
        "code": "",
        "industry": "",
        "name": "",
        "nature": "",
        status: '',
        remarkOne:'',
        remarkTwo:'',
        remarkThree:'',
        remarkFour:'',
        remarkFive:'',
      }
      this.$refs.searchForm.resetFields();
      // this.searchForm.pageNumber = 1;
      // this.searchForm.pageSize = 50;
      // 重新加载数据
      // this.getDataList();
      this.getDataListB();
    },

    clearSelectAll() {
      this.$refs.table.clearSelection(false);
    },
    changeOpenSearch() {
      this.openSearch = true;
    },

    downloadTemple() {
      window.location.href = process.env.BASE_URL + '标准单位库导入模板.xlsx';
    },
    //导出全部数据
    dropExportAll() {
      this.importing1 = true;
      let params ={
        "code": this.searchForm.code,
        "industry": this.searchForm.industry,
        "name":this.searchForm.name,
        "nature": this.searchForm.nature,
        "pageNo": this.searchForm.pageNumber,
        "pageSize": this.searchForm.pageSize,
        "status": this.searchForm.status,
      }

      exportAllBysXjInfo(params).then(res => {
        this.importing1 = false;
        // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
        const blob = new Blob([res], {type: 'charset=utf-8'});
        let url = window.URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '基础本信息.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 删除节点
        window.URL.revokeObjectURL(url); //释放该 url
      });
    },


    //导出所选数据
    dropExportData() {
      let ids = ''
      if (this.selectList.length <= 0) {
        this.$Message.warning('您还未选择要导出的数据');
        return;
      } else {
         ids = this.selectList.map((obj) => {
          return obj.id
        }).join(",");
        exportBatchMarketDataAPI({ids }).then((res) => {
          // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
          const blob = new Blob([res], {type: 'charset=utf-8'});
          let url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', '市场信息.xlsx');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 删除节点
          window.URL.revokeObjectURL(url); //释放该 url
        })
      }
    },
    importFormOk() {
      if (this.importForm.file == null) {
        this.$Message.info('请选择文件');
        return;
      }
      let formData = new FormData();
      // formData.append('importMode', this.importForm.importMode); // 添加参数
      formData.append('file', this.importForm.file);
      this.importing = true;
      formData.append('file', this.importForm.file);
      this.importing = true;
      exportAll(formData).then(res => {
        if (res.code === 200) {
          // this.$message.success("导入开始，请前往导入历史查看导入结果信息")
          this.importing = false;
          this.importFormView = false;
          this.tipMessage = "导入正在进行，点击此处或关闭弹窗点击导入历史按钮查看导入结果信息";
          this.type = 'success';
          this.importPromptVisible = true;
          this.$message.success('导入成功')
          this.handleSearchB()
        }
      });
    },

    importFormcCncel() {
      this.importForm.file = null;
      this.importFormView = false;
    },
    handleUpload(file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase();
      if (!(fileExt == 'xlsx' || fileExt == 'xls')) {
        this.$Notice.warning({
          title: '文件类型错误',
          desc:
              '所选文件‘ ' +
              file.name +
              ' ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的文件。'
        });
      } else {
        this.importForm.file = file;
      }
      // this.importForm.file = file;
      return false;
    },
    getDataList() {
      this.loading = true;
      getBysXjCompareList(this.searchForm)
          .then(res => {
            if (res.success) {
              this.loading = false;
              this.$message.success(res.message);
              this.data = res?.result?.result || [];
              this.total = res?.result?.total || 0;
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    getDataListB() {
      // this.loading = true;
      this.listLoading = true
      let params ={
        "code": this.searchForm.code,
        "industry": this.searchForm.industry,
        "name":this.searchForm.name,
        "nature": this.searchForm.nature,
        "pageNo": this.searchForm.pageNumber,
        "pageSize": this.searchForm.pageSize,
        "status": this.searchForm.status,
      }
      companiesPageAPI(params)
          .then(res => {
            this.listLoading = false
            if (res.success) {
              this.loading = false;
              this.data = res?.result?.records || [];
              this.total = res?.result?.total || 0;
              // this.tableheig()
              // if (this.data.length == 0 && this.searchForm.pageNumber > 1) {
              //   this.searchForm.pageNumber -= 1;
              //   this.getDataList();
              // }
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    add() {
      this.showDrawer = true;
      this.$refs.compareDetail.init(2)
    },
    submit(data,type){
      this.loading = true;
      let address = ''
      if (data.address && data.address.length>0) {
        address = data.address[data.address.length-1];
      }
      data.address =address
      if (type==2){
        delete data.id
        companiesAddAPI(data).then(res => {
          if (res.code == 200) {
            this.$message.success('添加成功');
            this.handleReset()
          }else {
            this.$message.error(res.message)
            this.handleReset()
          }
        })
      }else if  (type==1){
        let params = {
          "address": data.address,
          "code": data.code,
          "contactPerson":data.contactPerson,
          "contactPhone":data.contactPhone,
          "id": data.id,
          "industry":data.industry,
          "location":data.location,
          "name": data.name,
          "nature":data.nature,
          "status":data.status,
        }
        companiesUpdateAPI(params).then(res => {
          if (res.code == 200) {
            this.$message.success('编辑成功');
            this.handleReset()
          }else {
            this.$message.error(res.message)
            this.handleReset()
          }
        })
      }
    },
    remove(v) {
      this.$Modal.confirm({
        title: '确认删除',
        // 记得确认修改此处
        content: '您确认要删除该条数据?',
        loading: true,
        onOk: () => {
          // 删除
          companiesDeleteAPI({id: v.id }).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success('操作成功');
              this.getDataListB();
            }
          });
        }
      });
    },
    add() {
      this.openSearch =false
      this.$refs.compareDetail.init(2)
    },


    viewYdData(v) {
      this.openSearch =false
      this.$refs.compareDetail.init(1,v)
    },
    onRestWindow() {
      // this.columns = this.restTableCellWidth(this.columns_1)
      this.labelWidth = this.searchLabelWidth(110)
      this.tableWidth = this.searchLabelWidth(60)
    }
  },
  async mounted() {
    await this.getDictData()
    this.onRestWindow()
    window.addEventListener('resize', this.onRestWindow)
    let resource = JSON.parse(Cookies.get('userInfo')).resource;
    this.resource = resource
    this.init();

  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onRestWindow)
  }
};
</script>
<style lang="less">
// 建议引入通用样式 具体路径自行修改 可删除下面样式代码
@import '../../../../styles/table-common.less';
@import '../../../personInfo.less';

.tableContainer {
  width: 100%;
  height: calc(100% - 100px);
}

.search {
  .operation {
    margin-bottom: 2vh;
  }

  .select-count {
    font-weight: 600;
    color: #40a9ff;
  }

  .select-clear {
    margin-left: 10px;
  }

  .page {
    margin-top: 2vh;
  }

  .drop-down {
    margin-left: 5px;
  }
}

.all-height {
  height: 100%;
}
</style>
<style lang="less" scoped>
// 重构样式
/deep/ .ivu-form-item-label{
  display: flex;
  justify-content: right;
  width: 150px !important;
}
/deep/ .ivu-form-item {
  width: 100%;
  margin-bottom: 0.1rem;
  margin-right: 0 !important;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/deep/ .ivu-form-item-content {
  width: 100% !important;
  margin-left: 0 ! important;
}
/deep/ .ivu-select {
  width: 100% !important;
}
/deep/ .ivu-date-picker {
  width: 100% !important;
}
/deep/ .br {
  margin-top: 15px;
  bottom: -8px !important;
  .ivu-form-item-content {
    display: flex;
  }
}
.box-key {
  /deep/ .ivu-form-item-content {
    margin-left: 102px !important;
  }
}
</style>
